﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OnlineShop.Common;

namespace OnlineShop.Models.ViewModels
{
    public class ShoppingCartModel
    {
        public List<ProductModel> Products { get; set; }
        public double TotalPrice { get; set; }

        public void AddProduct(Product product, int quantity)
        {
            if (quantity <= 0)
                return;

            if (Products == null)
                Products = new List<ProductModel>();

            var productSeleted = Products.Where(pro => pro.Id == product.Id).SingleOrDefault();
            if (productSeleted == null)
            {
                Products.Add(product.ToModel(quantity));
            }
            else
            {
                productSeleted.Quantity += quantity;
            }

            CalculateTotalPrice();
        }

        public void RemoveProduct(int productId)
        {
            if (Products == null || Products.Count == 0)
                return;

            var product = Products.Where(pro => pro.Id == productId).Single();
            Products.Remove(product);

            CalculateTotalPrice();
        }

        public void CalculateTotalPrice()
        {
            if (Products == null || Products.Count == 0)
                TotalPrice = 0d;

            double total = 0;
            foreach (var product in Products)
                total += product.TotalPrice;

            TotalPrice = total;
        }

        public int GetQuantityProducts()
        {
            if (Products == null || Products.Count == 0)
                return 0;

            int quantity = 0;
            foreach (var pro in Products)
            {
                quantity += pro.Quantity;
            }

            return quantity;
        }

        public void UpdateQuantity(string values)
        {
            string[] arrValues = values.Split(',');

            for (int i = 0; i < Products.Count; i++)
            {
                string value = arrValues[i];
                int quantity = 0;
                Int32.TryParse(value, out quantity);

                if (quantity <= 0)
                    Products.RemoveAt(i);
                else
                {
                    Products[i].Quantity = quantity;
                }
            }

            CalculateTotalPrice();
        }
    }
}